package main

import (
	"log"
	"main/handlers"
	"main/routes"
	"main/taskexecutor"
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

func main() {
	// 加载配置
	handlers.LoadConfig()

	// 从viper读取数据库配置
	dbUser := viper.GetString("database.username")
	dbPass := viper.GetString("database.password")
	dbHost := viper.GetString("database.host")
	dbPort := viper.GetString("database.port")
	dbName := viper.GetString("database.dbname")

	// 根据配置生成连接字符串
	dsn := dbUser + ":" +
		dbPass + "@tcp(" +
		dbHost + ":" + dbPort + ")/" +
		dbName + "?charset=utf8mb4&parseTime=True&loc=Local"

	// 初始化数据库连接
	handlers.InitDB(dsn)

	// 创建任务执行器
	executor := taskexecutor.NewTaskExecutor(60*time.Second, 5) // 每60秒检查一次任务
	executor.Start()                                            // 启动执行器
	defer executor.Stop()                                       // 程序退出时停止执行器

	router := gin.Default()

	// CORS 中间件配置
	router.Use(cors.New(cors.Config{
		AllowOrigins:  []string{"http://localhost:3000", "http://192.168.3.88:3000"},
		AllowMethods:  []string{"GET", "PUT", "DELETE", "POST", "OPTIONS"},
		AllowHeaders:  []string{"Origin", "Content-Type", "Authorization"},
		ExposeHeaders: []string{"Content-Length"},
		MaxAge:        12 * time.Hour,
	}))

	// 注册受保护的路由
	routes.RegisterProtectedRoutes(router) // 确保这里调用的函数是正确的

	// 登录路由
	router.POST("/login", handlers.Login)

	// 启动服务器
	if err := router.Run("0.0.0.0:8080"); err != nil {
		log.Fatalf("Failed to run server: %v", err)
	}
}
